package com.cellulam.framework.fs.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;

@Component
public class AliOssClient {

    @Autowired
    private AliOssConfig ossConfig;


    public String upload(String name, InputStream inputStream) {
        return this.upload(null, name, inputStream);
    }

    /**
     * 上传文件
     *
     * @param path
     * @param name
     * @param inputStream
     * @return
     */
    public String upload(String path, String name, InputStream inputStream) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndPoint(), ossConfig.getAccessId(), ossConfig.getAccessKey());

// 创建存储空间。
        ossClient.createBucket(ossConfig.getBucketName());

        if(StringUtils.isEmpty(path)) {
            path = ossConfig.getDefaultPath();
        }
        String key =  path + "/" + name;

        // 上传文件流。
        ossClient.putObject(ossConfig.getBucketName(), key, inputStream);

        // 上传回调参数。
        ossClient.shutdown();

        return ossConfig.getStaticHost() + "/" + key;
    }
}
